import time
from dataclasses import dataclass
from typing import List
import requests


@dataclass
class Info(object):
    id: str
    filename: str
    update_time: str
    size: str


def get_millisecond():
    """
    :return: 获取精确毫秒时间戳,13位
    """
    millis = int(round(time.time() * 1000))
    return millis


def hum_convert(value) -> str:
    units = ["B", "KB", "MB",
             "GB", "TB", "PB"]
    size = 1024.0
    for i in range(len(units)):
        if (value / size) < 1:
            return "%.2f%s" % (value, units[i])
        value = value / size


class LuoPanSo(object):
    def __init__(self):
        self.headers = {
            "Accept": "application/json, text/plain, */*",
            "Accept-Language": "zh-CN,zh;q=0.9,en-GB;q=0.8,en;q=0.7",
            "Cache-Control": "no-cache",
            "Connection": "keep-alive",
            "Origin": "https://www.luomapan.com",
            "Pragma": "no-cache",
            "Referer": "https://www.luomapan.com/",
            "Sec-Fetch-Dest": "empty",
            "Sec-Fetch-Mode": "cors",
            "Sec-Fetch-Site": "cross-site",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36",
            "X-Authorization": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlvbmlkIjoib1RJWk02UE1xeW1oYjM4bEdkTWtINlhPS19nOCIsImlhdCI6MTY3NjE2OTUwNCwiZXhwIjoxNjc2Nzc0MzA0fQ.gGS7ZoMV-C0wysJUhI6sEY9BUGkmIdnkgK0MV1bJ5Hc",
            "sec-ch-ua": "^\\^Google",
            "sec-ch-ua-mobile": "?0",
            "sec-ch-ua-platform": "^\\^Windows^^"
        }

    @property
    def c_time(self):
        millis = int(round(time.time() * 1000))
        return millis

    def get_info_list(self, key_str):
        url = "https://fc-resource-node-api.krzb.net/api/v1/pan/search"
        params = {
            "version": "v2",
            "kw": key_str,
            "page": 1
        }
        response = requests.get(url, headers=self.headers, params=params).json()
        return [Info(data['res']['id'], data['res']['filename'],
                     data['res']['updatetime'], hum_convert(int(data['res']['size'])))
                for data in response['resources']]

    def check_ok(self, data: Info):
        url = "https://fc-resource-node-api.krzb.net/api/v1/pan/checkUrlValidFromBaidu"
        params = {
            "t": self.c_time,
            "version": "v2",
            "data": data.id
        }
        response = requests.get(url, headers=self.headers, params=params).json()
        if response.get(data.id):
            return True

    def resource_detail(self, id):
        url = "https://fc-resource-node-api.krzb.net/api/v1/pan/detail"
        params = {
            "version": "v2",
            "id": id,
            "size": "15",
            "parent": ""
        }
        response = requests.get(url, headers=self.headers, params=params).json()
        if response.get('haspwd'):
            return response['pwd']
        return None

    def get_pan_url(self, id, pwd):
        url = "https://fc-resource-node-api.krzb.net/api/v1/pan/url"
        params = {
            "version": "v2",
            "id": id
        }
        response = requests.get(url, headers=self.headers, params=params).json()
        if pwd:
            return response['data'] + f'?pwd={pwd}'
        return response['data']


def lp_tables_list(key_str: str) -> List[List]:
    TableDatas = []
    l = LuoPanSo()
    datas = l.get_info_list(key_str)
    for index, data in enumerate(datas):
        pwd = l.resource_detail(data.id)
        if l.check_ok(data):
            filename = data.filename
            size = data.size
            update_time = data.update_time
            pan_url = l.get_pan_url(data.id, pwd)
            TableDatas.append([index + 1, filename, size, update_time, pan_url])
    return TableDatas
